/**
 * 管理中心
 */
cc.Class({
    extends: cc.Component,

    properties: {
        spLotteryHotList: { 
            default: [],
            type: cc.SpriteFrame,   
        },	

        spLotteryIconList: { 
            default: [],
            type: cc.SpriteFrame
        },

        spLotteryStatusList: { 
            default: [],
            type: cc.SpriteFrame
        },

        spLotteryHotStatusList: { 
            default: [],
            type: cc.SpriteFrame
        },

        //快三图片列表
        spDiceList: { 
            default: [],
            type: cc.SpriteFrame
        },

        loginPopPrefab:cc.Prefab,
        _coning:false,
        _reCount:0,//重连次数
        _bFrist:true,//首次登陆
        curServerTime:0
    },

    // use this for initialization
    onLoad: function () {
        CL.MANAGECENTER = this.node.getComponent("ManageCenter");

        this.lottyerIconGruop = {
            '901': 0,  //big
            '801': 1,  //ssq
            '101': 2,  //redk3
            '102': 2,  //wink3
            '201': 3,  //hua115
            '202': 3,  //old115
            '301': 4,  //ssc
        };
        this.lottyerHotIconGruop = {
            '901': 0,  //big
            '801': 1,  //ssq
            '101': 2,  //redk3
            '102': 3,  //wink3
            '201': 4,  //hua115
            '202': 5,  //old115
            '301': 6,  //ssc
        };

        this.schedule(this.conUpdater,10);
    },

    conUpdater:function()
    {
        var recv = function(ret){
            if(ret.Code === 0){
                this.curServerTime = parseInt(ret.ServerTime/1000);
                if(!CL.NET.isConnect())
                {
                    cc.log("chat disconnect reconnect")
                    CL.MANAGECENTER.onConnectSK();
                }
            }
        }.bind(this);
        var data = {
            Token:User.getLoginToken(),
        }
        CL.HTTP.sendRequest(DEFINE.HTTP_MESSAGE.GETSERVERTIME, data, recv.bind(this),"POST"); 
    },

    getLotteryIconById:function(lottyID){
        var id = this.lottyerIconGruop[lottyID];
        return this.spLotteryIconList[id]; 
    },

    getLotteryHotById:function(lottyID){
        var id = this.lottyerHotIconGruop[lottyID];
        return this.spLotteryHotList[id]; 
    },

    getLotteryByStatus:function(state){
        //1今日开奖,2加奖,3奖上奖,4暂停销售
        return this.spLotteryStatusList[state]; 
    },

    getHotLotteryByStatus:function(state){
        //1今日开奖,2加奖,3奖上奖,4暂停销售
        return this.spLotteryHotStatusList[state]; 
    },

    getDiceSpriteFrameByNum:function(num){
        if(isNaN(num) || num == "undefined")
            num = 0;
        var inum = parseInt(num);    
        return this.spDiceList[inum]; 
    },

    //获取大厅列表
    getHallList: function(callback){
        var self = this;
        var recv = function recv(ret) {
            if (ret.Code !== 0 && ret.Code != 100) {
                cc.error(ret.Msg);
            } else {
                //登录模式 1：游客登录 2：手机号登录 3：微信登录 4：QQ登录 5：其他
                if(!User.getIsvermify())
                {
                    if(ret.IsVerifyToken)//验证通过
                    {
                        //cc.log("进入游戏自动登录");
                        User.setLoginToken(ret.Token);
                        User.upDateUserInfo(false,ret.LoginData);
                    }
                    else//游客登录
                    {
                        //cc.log("更新token"+ret.Token);
                        User.setLoginToken(ret.Token);
                        User.upDateUserInfo(true,"");
                    }
                    User.setIsvermify(ret.IsVerifyToken);
                }
 
                if(ret.Code != 100)
                {
                    //cc.log("chat connect ");
                    CL.MANAGECENTER.onConnectSK();
                }

                if (callback != null) {
                    callback(ret);
                }

                User.setSmGame(ret.GameData);
            }
        };
    
        var data = {
            Equipment:Utils.getEquipment(),
            Token:User.getLoginToken()
        };
        CL.HTTP.sendRequestRet(DEFINE.HTTP_MESSAGE.INIT, data, recv.bind(this),"POST");     
    },

    //注册登录界面
    gotoLoginPop:function(callBack)
    {
        if(this.loginPopPrefab)
        {
            var canvas = cc.find("Canvas");
            var loginPop = cc.instantiate(this.loginPopPrefab);
            canvas.addChild(loginPop);
            loginPop.getComponent("Login_login").setCallBack(callBack);
        }
        else
        {
            cc.log("loginPopPrefab加载失败");
        }
    },

    //解析聊天类的内容
    pushEvent:function(data){
        this.arData = [];
        if(Object.prototype.toString.call(data) !== "[object Array]") {
            this.arData.push(data);
        }
        else
            this.arData = data;

        if(this._Pushing)
            return;

            
        var dataTemp = this.arData.slice();
      
        for(var i=0;i<dataTemp.length;i++)
        {
            this._Pushing =true;
            var oneContent = dataTemp[i];
            var contentobj = "";
            var obj = "";
            var curTime = "";
    
            if(typeof oneContent !== 'object'){
                try {
                    contentobj = eval('(' + oneContent + ')');
                } catch (error) {
                    cc.log("chat RECV erro:"+error);
                    return;
                }
            }
            else
                contentobj = oneContent;
            try {
                obj = eval('(' + contentobj.data + ')');
            } catch (error) {
                return;
            }
    
            curTime = contentobj.time;
           
            var data0 = {
                data:obj,
                time:curTime,
            }
    
            switch (obj.MsgType)
            {
                case DEFINE.RECV_MSG_TYPE.MSG_TYPE_SYS:
                {         
                    window.Notification.emit("sysmsg_push",data0);
                }
                break;
                case DEFINE.RECV_MSG_TYPE.MSG_TYPE_USER:
                {
                    window.Notification.emit("newmsg_push",data0);
                }
                break;
                case DEFINE.RECV_MSG_TYPE.MSG_TYPE_PAO:
                {
                    window.Notification.emit("rPao_push",data0.data);
                }
                break;
                case DEFINE.RECV_MSG_TYPE.MSG_TYPE_OPEN:
                {
                    window.Notification.emit("rOpen_push",data0);
                }
                break;
                case DEFINE.RECV_MSG_TYPE.MSG_TYPE_LOTSTATE://同步彩种状态
                {
                    window.Notification.emit("rLotState_push",data0);
                }
                break;
                default:
                    break;
            }
        }
        this._Pushing = false;
    },

    //注册服务器返回信息事件
    initHandlers:function(){
        var self = this;
        CL.NET.addHandler("newmsg",function(data){
            self.pushEvent(data);
        });

        CL.NET.addHandler("sysmsg",function(data){
            self.pushEvent(data);
        });

        CL.NET.addHandler("otherjoin",function(data){//加入房间返回
            window.Notification.emit("otherjoin_push",data);
        });

        CL.NET.addHandler("rleave",function(data){//离开房间
            // cc.log("chat rleave:"+ data.data);
        });

        CL.NET.addHandler("rlogin",function(data){//登录返回
            var obj  = data;
            if(cc.sys.isNative)
            {
                if(Object.prototype.toString.call(data) !== "object")
                {
                    try {
                        obj  =  eval('(' + data + ')');
                    } catch (error) {
                        cc.log("chat rlogin data erro:"+error);
                        window.Notification.emit("rlogin_push",false);
                        return;
                    }
                }
            }
           
            if(obj.code == 0)//token效验失败
            {
                cc.log("chat token效验失败");
                CL.NET.close();
                window.Notification.emit("rlogin_push",false);
            }
            else if(obj.code == 1)
            {
                cc.log("chat 登陆成功");
                CL.NET.sio.connected = true;
                window.Notification.emit("rlogin_push",true);
            }
            else if(obj.code == 2)//后端未通知登录事件
            {
                cc.log("chat 后端未通知登录事件");
                CL.NET.close();
                window.Notification.emit("rlogin_push",false);
            }
        });
    },    

    //连接服务器
    onConnectSK:function(){
        cc.log("chat onConnectSK");
        if(this._bFrist)
        {
            this._bFrist = false;
            this.initHandlers();
        }
            
        if(CL.NET.isConnect())
        {
            cc.log("chat onconnectsk isconnect");
            return;
        }
        if(this._coning)
        {
            cc.log("chat onconnectsking");
            return;
        }
        else
        {
           // cc.log("chat onConnectSK 1");
            var self = this;
            var onConnectOK = function(){
                self._reCount = 0;
                self._coning = false;
                cc.log("chat onConnectOK");
                CL.NET.login();
            };
            var onConnectFailed = function(data){
                cc.log("chat onConnectFailed");
            
            };
            CL.NET.connect(onConnectOK,onConnectFailed);
            this._coning = true;
        }
    },

    reConnectSK:function(){
        cc.log("chat reConnectSK");
        if(CL.NET.isConnect())
        {
            cc.log("chat reConnectSK isconnect");
            return;
        }
        if(this._reCount >= 3)
        {
            cc.log("chat reConnectSK recount MAX");
            return;
        }

        this._reCount++;
        cc.log("chat reconnect :" + this._reCount);
        this.onConnectSK();
    },

    onDestroy:function(){
        this.unschedule(this.conUpdater);
    }

});
